import { openDB, closeDB, select } from '@/assets/database'
const state = {
	network: null //请求信息
}

const getters = {
	GET (state) {
		return state.network
	}
}

const mutations = {
	SET (state, network) {
		state.network = network
	}
}

const actions = {
	destroy ({state, commit}) {
		state.network && state.network.destroy()
		commit('SET', null)
	},
	async navigateToProgram ({commit, dispatch}, {id, redirect}) {
		dispatch('destroy')
		try{
			const Network = require('@/assets/api/global.js').default
			const inSource = require('@/assets/api/source.js').default
			await openDB()
			const data = await select('source')
			closeDB()
			const list = inSource.concat(data.list.map(item => Object.assign({}, eval('(' + decodeURIComponent(item.rule) + ')'), {dataId: item.id} )))
			const sourceIndex = list.findIndex(item => item.id == id)
			if ( sourceIndex > -1 ) {
				const source = list[sourceIndex]
				const network = new Network(source)
				await network.init()
				commit('SET', network)
				uni.navigateTo({
					url: '/pages/find/index' + (redirect ? '?redirect=' + encodeURIComponent(redirect) : ''),
					animationType: 'slide-in-bottom',
					animationDuration: 200,
				})
			} else {
				uni.showToast({
					title: '请确认是否安装了对应程序',
					icon: 'none'
				})
			}
		}catch(e){
			closeDB()
			uni.showToast({
				title: e.message,
				icon: 'none'
			})
		}
	}
}

export default {
    namespaced: true,
    state,
    getters,
    mutations,
	actions
}